import { userLogin } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils'
import { resetRouter } from '@/router'

const getDefaultState = () => {
    return {
        u_info: getToken(),
    }
}
const state = getDefaultState()
const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_USERINFO: (state, u_info) => {
        state.u_info = u_info
    },
}

const actions = {
    login({ commit }, userInfo) {
        const { username, password } = userInfo
        return new Promise((resolve, reject) => {
            userLogin({ username: username.trim(), password: password }).then(response => {
                const userInfo = JSON.stringify(response)
                commit('SET_USERINFO', response)
                setToken(userInfo)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // user logout
    logout({ commit, state }) {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            removeToken() // must remove  token  first
            commit('RESET_STATE')
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}

